package com.birdboot.core;

import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 该线程任务负责与指定的客户端进行HTTP交互
 * HTTP协议要求浏览器与服务端采取"一问一答"的模式。对此，这里的处理流程分为三步:
 * 1:解析请求
 * 2:处理请求
 * 3:发送响应
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            //1 解析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            HttpServletResponse response = new HttpServletResponse(socket);

            //2 处理请求
            //获取请求的抽象路径
            String path = request.getUri();
            System.out.println(path);
            //定位当前项目的类加载路径
            File baseDir = new File(
                    ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            //定位类加载路径下的static目录
            File staticDir = new File(baseDir, "static");
            File file = new File(staticDir, path);

            /*
                V7改造
                1:将原来在这里定义的两个局部变量statusCode和statusReason删除
                2:将处理结果设置到response对应的属性上
                3:将发送响应的操作移动到HttpServletResponse的response方法中
                  并在第三步发送响应时改为调用response方法发送响应
             */
            if(file.isFile()){
                //由于响应对象中状态代码和描述默认值为200，OK因此正确情况下不用再设置
                response.setContentFile(file);
            }else{
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File(staticDir,"404.html");
                response.setContentFile(file);
            }

            //3 发送响应
            response.response();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }



}




